#!/usr/bin/env python

import os, sys
import mad
import glob, math
import gdata
import gdata.youtube.service
import getpass

developer_key = "AI39si7BsacKDuEdC91xBvNoov44fm_hGvr6EQAVX9LktyhnZhAilTMyhQ9OAAhkkebVs_BewtHpjkjzsrNz7KETSLr6DJhWTQ"
clientid = "emlynoregan"

def executecmd(cmdstring):
	print cmdstring
	os.system(cmdstring)
	
if (len(sys.argv) > 1):
	moviepath = "*" + sys.argv[1]
	#title = sys.argv[2]
	#description = sys.argv[3]
	category = 'Music'
else:
	print("Usage: upload2youtube path-to-video [title prefix] [description]") # title description category")
	sys.exit(1)

titleprefix = ""
if (len(sys.argv) > 2):
	titleprefix = sys.argv[2] + " - "
 
adescription = "automated upload"
if (len(sys.argv) > 3):
	adescription = sys.argv[3]

password = getpass.getpass("Youtube Password: ")


paths = []
for infile in glob.glob( moviepath ):	
	paths.append(infile)

for infile in paths:	
	# A complete client login request
	yt_service = gdata.youtube.service.YouTubeService()
	yt_service.email = 'emlynoregan@gmail.com'
	yt_service.password = password
	yt_service.source = 'upload2youtube python'
	yt_service.developer_key = developer_key
	yt_service.client_id = clientid
	yt_service.ProgrammaticLogin()

	my_media_group = gdata.media.Group(
	  title=gdata.media.Title(text=titleprefix + infile),
	  description=gdata.media.Description(description_type='plain',
                                      text=adescription),
	  keywords=gdata.media.Keywords(text=category),
	  category=[gdata.media.Category(
	      text=category,
	      scheme='http://gdata.youtube.com/schemas/2007/categories.cat',
	      label=category)],
	  player=None,
	  private=gdata.media.Private()
	)

	video_entry = gdata.youtube.YouTubeVideoEntry(media=my_media_group)

	video_file_location = infile

	print ("Beginning Upload of %s" % (video_file_location))

	new_entry = yt_service.InsertVideoEntry(video_entry, video_file_location)

	print ("Finished Upload of %s" % (video_file_location))

	upload_status = yt_service.CheckUploadStatus(new_entry)

	if upload_status is not None:
	  	print("Status: %s (%s)" % (upload_status[0], upload_status[1]))
	else:
		print ("Success.")


print ("Done upload2youtube")
